#!/usr/bin/env python3
import argparse
import random
import socket

from myTunnel_header import MyTunnel
from scapy.all import IP, TCP, Ether, get_if_hwaddr, get_if_list, sendp


def find_eth_interface():
    """Find the first interface containing 'eth0'"""
    for iface in get_if_list():
        if "eth0" in iface:
            return iface
    print("Error: eth0 interface not found")
    exit(1)


def main():
    parser = argparse.ArgumentParser(description='Send packets with optional tunnel header')
    parser.add_argument('dest_ip', type=str, help='Destination IP address')
    parser.add_argument('payload', type=str, help='Message payload to include')
    parser.add_argument('--tunnel-id', type=int, default=None, 
                      help='Tunnel ID for MyTunnel header (optional)')
    args = parser.parse_args()

    target_ip = socket.gethostbyname(args.dest_ip)
    tunnel_id = args.tunnel_id
    iface = find_eth_interface()

    # Build packet
    base_pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
    
    if tunnel_id is not None:
        print(f"Sending on {iface} to tunnel {tunnel_id}")
        full_pkt = base_pkt / MyTunnel(dst_id=tunnel_id) / IP(dst=target_ip) / args.payload
    else:
        print(f"Sending on {iface} to IP {target_ip}")
        full_pkt = base_pkt / IP(dst=target_ip) / TCP(
            dport=1234, 
            sport=random.randint(49152, 65535)
        ) / args.payload

    full_pkt.show2()
    sendp(full_pkt, iface=iface, verbose=False)


if __name__ == '__main__':
    main()